package com.limingru.online_class.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.limingru.online_class.common.Constant;
import com.limingru.online_class.common.Result;
import com.limingru.online_class.common.ResultGenerator;
import com.limingru.online_class.common.ServiceResultEnum;
import com.limingru.online_class.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.security.auth.login.Configuration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = JWTUtil.checkToken(token);
            if (claims == null) {
                Result result = ResultGenerator.generateFailResult(ServiceResultEnum.TOKEN_EXPIRED.getText());
                sendResponse(response, result);
                return false;
            }
            Date expiration = claims.getExpiration();
            Date now = new Date();
            Integer id = (Integer) claims.get("id");
            String name = (String) claims.get("name");
            if (expiration.getTime() - now.getTime() < Constant.EXPIRE) {
                request.setAttribute("userId", id);
                request.setAttribute("userName", name);
                return true;
            }
            sendResponse(response, ResultGenerator.generateFailResult(501, "token失效，请重新登录"));
            return false;
        }

        sendResponse(response, ResultGenerator.generateFailResult(501, "没有token"));
        return false;
    }

    private void sendResponse(HttpServletResponse response, Result result) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(s);
            writer.close();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
